package com.ironman.original.generator;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.ironman.common.OriginalSimpleData;
import com.ironman.common.threadpool.ThreadPool;
import com.ironman.event.topic.dami.OriginalTopic;
import org.noear.dami.Dami;
import org.noear.snack.ONode;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public abstract class OriginalDataGenerator {

    public void start(String mHmId, Function<String, Boolean> function) {
        ThreadPool.SCHEDULED_EXECUTOR.scheduleAtFixedRate(() -> {
            Date ts = DateUtil.beginOfSecond(new Date());
            String data = generate();
            String dataType = dataType();
            ONode node = ONode.newObject()
                    .set("dataType", dataType)
                    .set("hmId", mHmId)
                    .set("ts", DateUtil.format(ts, DatePattern.NORM_DATETIME_PATTERN))
                    .set("data", data);
            String json = node.toJson();
            Boolean published = function.apply(json);
            log(published, JSONUtil.toJsonPrettyStr(json));
            Dami.<OriginalSimpleData, Void>bus().send(
                    OriginalTopic.ORIGINAL_TOPIC + dataType,
                    OriginalSimpleData.builder().ts(ts).data(data).build()
            );
        }, 5, 1, TimeUnit.SECONDS);
    }

    abstract String dataType();

    abstract String generate();

    abstract void log(Boolean published, String data);
}
